package com.desmao.db;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class DataSourceAspect {

    private Logger logger = LoggerFactory.getLogger(DataSourceAspect.class);


    @Before("execution(* com.desmao.mapper..*.*(..))")
    public void before(JoinPoint point) {

        Object target = point.getTarget();
        String method = point.getSignature().getName();

        Class<?>[] classz = target.getClass().getInterfaces();

        Class<?>[] parameterTypes = ((MethodSignature) point.getSignature()).getMethod().getParameterTypes();
        try {
            Method m = classz[0].getMethod(method, parameterTypes);
            if (m != null && m.isAnnotationPresent(DBSource.class)) {
                DBSource data = m.getAnnotation(DBSource.class);
                DynamicDataSourceHolder.putDataSource(data.value());
                logger.info("-------datasource：{}------", data.value());
            }

        } catch (Exception e) {
            logger.error("AOP Register Intercept Failed.！",e);
        }
    }

    @After("execution(* com.desmao.mapper..*.*(..))")
    public void after(JoinPoint point){

        Object target = point.getTarget();
        String method = point.getSignature().getName();

        Class<?>[] classz = target.getClass().getInterfaces();

        Class<?>[] parameterTypes = ((MethodSignature) point.getSignature()).getMethod().getParameterTypes();
        try {
            Method m = classz[0].getMethod(method, parameterTypes);
            if (m != null && m.isAnnotationPresent(DBSource.class)) {
                DynamicDataSourceHolder.clear();
                logger.info("-------Clean ThreadLocal------");
            }

        } catch (Exception e) {
            logger.error("AOP Register Intercept Failed.！",e);
        }
    }
}